/*
 * FQN.java
 * 
 * last update: 01.02.2010 by Florea Mihai
 * 
 * author:	Alec(panovici@elcom.pub.ro)
 * 			Florea Mihai(florea.mihai@gmail.com)
 * 
 * Obs:
 */


package engine;


class FQN {
	public Object node;
	public FQN next;

	public FQN(Object node) {
		this(node, null);
	}

	public FQN (Object node, FQN next) {
		this.node = node;
		this.next = next;
	}

	public int len() {
		if (next == null) return 1;
		return 1 + next.len();
	}

	public boolean isIndex() {
		return node instanceof Expression;
	}

	public boolean isName() {
		return node instanceof String;
	}

	/**
	 * Returns the FQN associated with a given string:
	 * this string must contain _only_ names and integer number indexes.
	 * The string's for is the one given from the IDE watch tree:
	 * for module array dummy, register dummy[5].reg1 will have the
	 * associated string: @top.dummy.dummy[5].reg1 , because
	 * there is a tree node for dummy[5] and one for the array
	 * itself, called dummy.
	 */
	public static FQN parseString(String s) throws ParseException {
		xConsole.debug("FQN parsing: " + s);
		try {
			if (s.charAt(0) == '.') return parseString(s.substring(1, s.length()));
			int nextNode, nextBrace;
			if ((nextBrace = s.indexOf(']')) < (nextNode = s.indexOf('.')) &&
					(nextBrace != -1)) { //index
				if(nextBrace+1 != nextNode && nextNode != -1)
					throw new ParseException(); // not a "]."
				FQN fqn = new FQN (new Constant(null,
						new BitVector(s.substring(s.indexOf('[')
								+ 1,
								nextBrace),
								10,
								-1,
								true,
								false),
								null));
				if(nextNode != -1) fqn.next = parseString(s.substring(nextNode +1));
				return fqn;
			} else {
				if(nextNode == -1) nextNode = s.length();
				FQN fqn = new FQN(s.substring(0, nextNode));
				if(nextNode != s.length())
					fqn.next = parseString(s.substring(nextNode+1));
				return fqn;
			}
		} catch (IndexOutOfBoundsException iobex) {
			xConsole.dumpStack(iobex);
			throw new ParseException();
		}
	}

	public String toString () {
		return (node instanceof String ? node : "[" + node + "]") +
		(next == null ? "" : (next.isIndex() ? "" : ".") + next.toString());
	}
}
